package cn.dengta.webapp.trade.service;

import java.util.List;

import cn.dengta.common.model.Bean;
import cn.dengta.common.model.TimeInterval;
import cn.dengta.webapp.base.entity.BaseEntity;
import cn.dengta.webapp.base.service.BaseServiceImpl;
import cn.dengta.webapp.base.util.MybatisUtil;
import cn.dengta.webapp.trade.dao.UserLevelLogDao;
import cn.dengta.webapp.trade.entity.UserLevelLog;
import cn.dengta.webapp.user.entity.userLevel.UserLevelRule.UserLevelRuleType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.codeplayer.util.*;
import org.springframework.stereotype.Service;

import static cn.dengta.webapp.trade.entity.UserLevelLog.*;

/**
 * 用户等级记录表 服务实现类
 *
 * @author lgy
 * @since 2022-11-28
 */
@Service
public class UserLevelLogService extends BaseServiceImpl<UserLevelLog, UserLevelLogDao, Long> {

	public QueryWrapper<UserLevelLog> popWrapper(Long userId, UserLevelRuleType ruleType, BaseEntity bean, Integer changeExp, TimeInterval addTimeInterval) {
		QueryWrapper<UserLevelLog> wrapper = new QueryWrapper<>();
		wrapper.eq(userId != null, USER_ID, userId)
				.eq(ruleType != null, RULE_TYPE, ruleType)
				.eq(StringUtil.notEmpty(X.map(bean, BaseEntity::entityName)), ASSOC_TYPE, X.map(bean, BaseEntity::entityName))
				.eq(X.map(bean, BaseEntity::getId) != null, ASSOC_ID, X.map(bean, BaseEntity::getId))
				.eq(changeExp != null, EXP, changeExp);
		MybatisUtil.wrapperInterval(wrapper, ADD_TIME, addTimeInterval);
		return wrapper;
	}

	/**
	 * 查询用户指定时间区间内指定任务钻石规则的记录数量
	 */
	public int getCountOfLog(Long userId, UserLevelRuleType ruleType, TimeInterval addTimeInterval) {
		return NumberUtil.getInt(count(popWrapper(userId, ruleType, null, null, addTimeInterval)), 0);
	}

	public int getCountOfLog(Long userId, UserLevelRuleType ruleType, BaseEntity bean, TimeInterval addTimeInterval) {
		return NumberUtil.getInt(count(popWrapper(userId, ruleType, bean, null, addTimeInterval)), 0);
	}

	public UserLevelLog getLastLog(Long userId, UserLevelRuleType ruleType, TimeInterval addTimeInterval) {
		QueryWrapper<UserLevelLog> wrapper = popWrapper(userId, ruleType, null, null, addTimeInterval);
		wrapper.last("ORDER BY ID LIMIT 1");
		return selectOne(wrapper);
	}

	public List<UserLevelLog> findLatestLog(Long userId, UserLevelRuleType ruleType, TimeInterval addTimeInterval, Integer size) {
		QueryWrapper<UserLevelLog> wrapper = popWrapper(userId, ruleType, null, null, addTimeInterval);
		if (size != null) {
			wrapper.last("LIMIT " + size);
		}
		wrapper.orderByDesc(ID);
		return baseDao.selectList(wrapper);
	}

	public void saveOrUpdate(UserLevelLog entity) {
		super.saveOrUpdate(entity, Bean.hasId(entity));
	}

}
